package HallCallStrategy;

import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

import Dispatcher.ElevatorStatus;

public class SmartHallCallStrategy implements HallCallStrategy {

	public SmartHallCallStrategy() {
		super();
	}

	@Override
	public int getBestElevator(int requestedFloor, int direction,
			ConcurrentHashMap<Integer, ElevatorStatus> status) {
		//if there is just one elevator, return its index
		if (status.size() == 1) {
			if (status.values().iterator().hasNext()) {
				return status.values().iterator().next().getId();
			}
		}
		
		//if any elevator is free, choose it
		for (int i : status.keySet()) {
			if (status.get(i).getState() == 1) {
				return i;
			}
		}
		
		//else choose closest elevator
		//first find elevator moving in same direction
		ArrayList<Integer> sameDirIndexes = new ArrayList<Integer>();
		for (int i : status.keySet()) {
			if (status.get(i).getDirection() == direction) {
				sameDirIndexes.add(i);
			}
		}
		//now return closest one moving in same direction
		if (direction == 1) {
			int best = 0;
			for (int i : sameDirIndexes) {
				ElevatorStatus s = status.get(i);
				int sNextDest = s.getNextDest();
				if (sNextDest > best) {
					best = sNextDest;
				}
			}
			return best;
		}
		else if (direction == -1) {
			int best = 99;
			for (int i : sameDirIndexes) {
				ElevatorStatus s = status.get(i);
				int sNextDest = s.getNextDest();
				if (sNextDest < best) {
					best = sNextDest;
				}
			}
			return best;
		}
		
			
		//else - no elevator found - return 0
		return 0;
	}

}
